<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-row :gutter="5">
        <el-col :span="4">
          <el-form-item label="项目名称" prop="projectName">
            <el-input
              v-model="queryParams.projectName"
              placeholder="请输入项目名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="项目编号" prop="projectNumber">
            <el-input
              v-model="queryParams.projectNumber"
              placeholder="请输入项目编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="项目来源" prop="source">
            <el-select v-model="queryParams.source" placeholder="请选择项目来源" clearable>
              <el-option
                v-for="dict in dict.type.sci_pjt_source"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="项目级别" prop="level">
            <el-select v-model="queryParams.level" placeholder="请选择项目级别" clearable>
              <el-option
                v-for="dict in dict.type.sci_pjt_leavel"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="研究类型" prop="researchType">
            <el-select v-model="queryParams.researchType" placeholder="请选择研究类型" clearable>
              <el-option
                v-for="dict in dict.type.sci_pjt_reasearch_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="合作形式" prop="cooperationType">
            <el-select v-model="queryParams.cooperationType" placeholder="请选择合作形式" clearable>
              <el-option
                v-for="dict in dict.type.sci_pjt_cooperation_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>


      </el-row>

      <el-row :gutter="5">
        <el-col :span="4">
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="daterangeStartDate"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="结题时间">
            <el-date-picker
              v-model="daterangeEndDate"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="科研方向" prop="deptId">
            <el-select
              v-model="queryParams.deptId"
              placeholder="请选择所属科研方向"
              @change="handleQueryDeptChange"
              clearable
            >
              <el-option
                v-for="dept in deptList"
                :key="dept.deptId"
                :label="dept.deptName"
                :value="dept.deptId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="负责人" prop="manager">
            <el-select
              v-model="queryParams.manager"
              placeholder="请选择负责人"
              clearable
            >
              <el-option
                v-for="user in queryUserList"
                :key="user.userId"
                :label="user.nickName"
                :value="user.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="承担单位" prop="affiliation">
            <el-input
              v-model="queryParams.affiliation"
              placeholder="请输入承担单位"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="项目状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择项目状态" clearable>
              <el-option
                v-for="dict in dict.type.sci_pjt_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="5">
        <el-col :span="4">
          <el-form-item label="项目性质" prop="projectType">
            <el-input
              v-model="queryParams.projectType"
              placeholder="请输入项目性质"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4" :offset="16">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:project:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:project:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:project:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="项目ID" align="center" prop="projectId" /> -->
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="项目编号" align="center" prop="projectNumber" />
      <el-table-column label="项目来源" align="center" prop="source">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sci_pjt_source" :value="scope.row.source"/>
        </template>
      </el-table-column>
      <el-table-column label="项目级别" align="center" prop="level">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sci_pjt_leavel" :value="scope.row.level"/>
        </template>
      </el-table-column>
      <el-table-column label="研究类型" align="center" prop="researchType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sci_pjt_reasearch_type" :value="scope.row.researchType"/>
        </template>
      </el-table-column>
      <el-table-column label="承担单位" align="center" prop="affiliation" />
      <el-table-column label="所属科研方向" align="center" prop="deptName" />
      <el-table-column label="项目负责人" align="center" prop="nickName" />
      <el-table-column label="开始时间" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结题时间" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合作形式" align="center" prop="cooperationType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sci_pjt_cooperation_type" :value="scope.row.cooperationType"/>
        </template>
      </el-table-column>
      <el-table-column label="总经费" align="center" prop="totalFunding" />

      <el-table-column label="项目状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sci_pjt_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="文件URL" align="center" prop="fileUrl" /> -->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="项目性质" align="center" prop="projectType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sci_pjt_xz" :value="scope.row.projectType"/>
        </template>
      </el-table-column>
      <el-table-column label="预期目标" align="center" prop="expectedGoal" />
      <el-table-column label="操作"fixed="right" width="160" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:project:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:project:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目表维护对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="100px"
        >
        <el-row :gutter="15">
          <el-col :span="6">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" clearable
                :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目编号" prop="projectNumber">
              <el-input v-model="form.projectNumber" placeholder="请输入项目编号" clearable
                :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目来源" prop="source">
              <el-select v-model="form.source" placeholder="请输入项目来源" clearable :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.sci_pjt_source"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目级别" prop="level">
              <el-select v-model="form.level" placeholder="请输入项目级别" clearable :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.sci_pjt_leavel"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="研究类型" prop="researchType">
              <el-select v-model="form.researchType" placeholder="请输入研究类型" clearable
                :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.sci_pjt_reasearch_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目性质" prop="projectType">
              <el-select v-model="form.projectType" placeholder="请选择项目性质" clearable
                :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.sci_pjt_xz"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目状态" prop="status">
              <el-select v-model="form.status" placeholder="请输入项目状态" clearable :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.sci_pjt_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="总经费" prop="totalFunding">
              <el-input v-model="form.totalFunding" placeholder="请输入总经费" clearable
                :style="{width: '100%'}">
                <template slot="append">万元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="自筹经费" prop="selfRaisedFunds">
              <el-input v-model="form.selfRaisedFunds" placeholder="请输入自筹经费" clearable
                :style="{width: '100%'}">
                <template slot="append">万元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="财政拨款" prop="governmentGrant">
              <el-input v-model="form.governmentGrant" placeholder="请输入财政拨款" clearable
                :style="{width: '100%'}">
                <template slot="append">万元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="承担单位" prop="affiliation">
              <el-input v-model="form.affiliation" placeholder="请输入承担单位位" clearable
                :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合作形式" prop="cooperationType">
              <el-select v-model="form.cooperationType" placeholder="请输入合作形式" clearable
                :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.sci_pjt_cooperation_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合作单位" prop="cooperationUnit">
              <el-input v-model="form.cooperationUnit" placeholder="请输入合作单位" clearable
                :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="6">
            <el-form-item label="科研方向" prop="deptId">
              <el-select v-model="form.deptId" @change="handleDeptChange"
              multiple
              placeholder="请输入科研方向" clearable :style="{width: '100%'}">
                <el-option
                  v-for="dept in deptList"
                  :key="dept.deptId"
                  :label="dept.deptName"
                  :value="dept.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目负责人" prop="manager">
              <el-select v-model="form.manager" placeholder="请输入项目负责人" clearable :style="{width: '100%'}">
                <el-option
                  v-for="user in userList"
                  :key="user.userId"
                  :label="user.nickName"
                  :value="user.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker v-model="form.startDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                :style="{width: '100%'}" placeholder="请选择开始日期" clearable></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结题日期" prop="endDate">
              <el-date-picker v-model="form.endDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                :style="{width: '100%'}" placeholder="请选择结题日期" clearable></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-form-item label="相关文档资料" prop="fileUrl">
              <file-upload v-model="form.fileUrl"/>
          </el-form-item>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"
            :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject } from "@/api/sci/project";
import { listDept } from '@/api/system/dept';
import { listUserByDeptId,listUser } from '@/api/system/user';

export default {
  name: "Project",
  dicts: ['sci_pjt_cooperation_type', 'sci_pjt_source', 'sci_pjt_reasearch_type', 'sci_pjt_leavel', 'sci_pjt_status','sci_pjt_xz'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目表维护表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 预期目标时间范围
      daterangeStartDate: [],
      // 预期目标时间范围
      daterangeEndDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        projectNumber: null,
        source: null,
        level: null,
        researchType: null,
        manager: null,
        startDate: null,
        endDate: null,
        cooperationType: null,
        totalFunding: null,
        affiliation: null,
        deptId: null,
        status: null,
        fileUrl: null,
        projectType: null,
        expectedGoal: null
      },
      deptList: [],
      userList: [],
      queryUserList: [],
      formUserList: [],
      // 表单参数
      form: {
        deptId: [],
      },
      // 表单校验
      rules: {
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],

        source: [
          { required: true, message: "项目来源，关联数据字典不能为空", trigger: "change" }
        ],
        level: [
          { required: true, message: "项目级别不能为空", trigger: "change" }
        ],
        researchType: [
          { required: true, message: "研究类型，关联数据字典不能为空", trigger: "change" }
        ],
        manager: [
          { required: true, message: "项目负责人不能为空", trigger: "change" }
        ],
        startDate: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "结题时间不能为空", trigger: "blur" }
        ],
        cooperationType: [
          { required: true, message: "合作形式不能为空", trigger: "change" }
        ],
        affiliation: [
          { required: true, message: "承担单位不能为空", trigger: "blur" }
        ],
        totalFunding: [
          { required: true, message: "总经费不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "所属科研方向不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "项目状态不能为空", trigger: "change" }
        ],
        projectType: [
          { required: true, message: "项目性质不能为空", trigger: "blur" }
        ],
        expectedGoal: [
          { required: true, message: "预期目标不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.getDeptList();
    this.getUserList();
  },
  methods: {
    /** 查询项目表维护列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeStartDate && '' != this.daterangeStartDate) {
        this.queryParams.params["beginStartDate"] = this.daterangeStartDate[0];
        this.queryParams.params["endStartDate"] = this.daterangeStartDate[1];
      }
      if (null != this.daterangeEndDate && '' != this.daterangeEndDate) {
        this.queryParams.params["beginEndDate"] = this.daterangeEndDate[0];
        this.queryParams.params["endEndDate"] = this.daterangeEndDate[1];
      }
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        projectName: null,
        projectNumber: null,
        source: null,
        level: null,
        researchType: null,
        manager: null,
        startDate: null,
        endDate: null,
        cooperationType: null,
        totalFunding: null,
        affiliation: null,
        deptId: [],
        status: null,
        isDeleted: null,
        approvedBy: null,
        approvedAt: null,
        approvalStatus: null,
        extendField: null,
        fileUrl: null,
        log: null,
        createdBy: null,
        updatedBy: null,
        createdTime: null,
        updatedTime: null,
        remark: null,
        projectType: null,
        expectedGoal: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeStartDate = [];
      this.daterangeEndDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      try {
        const projectId = row.projectId || this.ids;
        const response = await getProject(projectId);
        const projectData = response.data;

        // 关键修改：确保 deptId 是数组类型
        if (typeof projectData.deptId === 'string') {
          projectData.deptId = projectData.deptId.split(',').map(Number);
        } else if (!Array.isArray(projectData.deptId)) {
          projectData.deptId = projectData.deptId ? [Number(projectData.deptId)] : [];
        } else {
          projectData.deptId = projectData.deptId.map(Number);
        }
        this.form.deptId = projectData.deptId;
        await this.handleDeptChange(this.form.deptId); // 等待 handleDeptChange 完成
        this.reset();
        this.form = { ...projectData }; // 使用展开运算符避免引用污染
        this.open = true;
        this.title = "修改项目信息";
      } catch (error) {
          console.error("获取设备信息失败", error);
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 将 form.deptId 从数组转换为逗号分隔的字符串
          if (Array.isArray(this.form.deptId)) {
            this.form.deptId = this.form.deptId.join(',');
          }
          if (this.form.projectId != null) {
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      this.$modal.confirm('是否确认删除项目表维护编号为"' + projectIds + '"的数据项？').then(function() {
        return delProject(projectIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/project/export', {
        ...this.queryParams
      }, `project_${new Date().getTime()}.xlsx`)
    },
    getDeptList() {
      listDept().then(response => {
        this.deptList = response.data;
      });
    },
    getUserList() {
      listUser().then(res => {
            console.log("获取用户", res);
            this.userList = res.rows;
            // this.queryUserList=res.rows
        });
    },

    async handleDeptChange(deptId) {
      this.form.manager = null; // 置空用户ID
      if (deptId && deptId.length > 0) {
          try {
            const deptIds = deptId.join(',');
            const response = await listUserByDeptId(deptIds);
            this.userList = response.data;
          } catch (error) {
            console.error("获取用户列表失败", error);
          }
        } else {
          this.userList = [];
        }
    },
    handleQueryDeptChange(deptId) {
      this.queryParams.manager = null; // 置空用户ID
      if (deptId) {
        listUserByDeptId(deptId).then(response => {
          this.queryUserList = response.data;
        });
      } else {
        this.queryUserList = [];
      }
    },
  }
};
</script>
